<script setup lang="ts">
import { watch, reactive, ref, onMounted, computed } from "vue";

import type { Ref } from 'vue';
//引入管理员相关的小仓库
import useAdminStore from '@/store/modules/admin'; // 命名导入
let adminStore = useAdminStore();
import useStudentStore from "@/store/modules/student";
import { ElMessage } from "element-plus";
let studentStore = useStudentStore();
// 定义数据类型
interface ClassData {
  classId: number;
  adminUsername: string;
  className: string;
  classStudentNumber: number;
  adminId: number;
}


// 定义表格数据的类型
interface GroupData {
  groupId: number;
  studentId: number;
  groupName: string;
  groupProName: string;
  groupScore: number;
  groupIsAvailable: number;
  groupLeader: string;
  groupNotice: string | null;
  groupFinish: number;
  classId: number;
  giteeUrl: string;
}

//进行班级小组渲染
const value = ref('')
// 初始化 options
const options = ref<Array<{ value: number; label: string }>>([]);

// 生成 options 函数
const generateOptionsFromTableData = () => {
  const newOptions = adminStore.tableData.map((item: ClassData) => ({
    value: item.classId,
    label: item.className,
  }));
  options.value = newOptions;
};


// 在组件挂载时调用生成 options
onMounted(async () => {
  await adminStore.fetchTableData({ page: 1, pageSize: 10 });
  generateOptionsFromTableData();
});



//分页相关
let page = reactive({ currentPage: 1, pageSize: 10, total: 0 });
// 初始化 tableData 使用正确的类型
const tableData: Ref<GroupData[]> = ref([]);

// 根据 classId 获取数据
const fetchDataByClassId = async () => {
  // 打印 adminStore 以确认方法存在
  console.log('AdminStore:', adminStore);
  if (value.value !== null) {
    await adminStore.fetchTableGroupsData({
      classId: value.value,
      page: page.currentPage,
      pageSize: page.pageSize,
    });
    tableData.value = adminStore.tableGroupsData; // 更新表格数据
  }
};

// 监听 value 的变化
watch(value, async (newVal) => {
  console.log('Value changed:', newVal); // 添加日志
  if (newVal !== null) {
    await fetchDataByClassId();
  }
});

// 计算属性用于转换 groupFinish 的值
const finishStatusMap = computed(() => {
  return {
    0: '未开始',
    1: '需求分析进行中',
    2: '概要设计进行中',
    3: '详细设计',
    4: '软件编码',
    5: '测试',
    6: '完成'
  };
});

// 辅助函数用于获取完成进度描述
const getFinishStatus = (status: number): string => {
  // @ts-ignore
  return finishStatusMap.value[status] || '未知状态';
};

// 计算属性用于转换 groupFinish 的值
const isavailableStatusMap = computed(() => {
  return {
    0: '未立项',
    1: '立项成功'
  };
});
// 辅助函数用于获取立项信息
const getIsavailableStatus = (status: number): string => {
  console.log(tableData);
  // @ts-ignore
  return isavailableStatusMap.value[status] || '未知状态';
};







//导出小组得分
const exportScore = async () => {
  try {
    await adminStore.exportGroups(value.value); // 假设 classId 是你需要传递的参数
  } catch (error) {
    console.error('下载失败:', error);
    throw new Error('下载失败');
  }

}



const getScore = (index: number, row: GroupData) => {
  // 将当前行的数据赋值给 selectedRow
  scoreForm.groupId = row.groupId;
  scoreForm.groupName = row.groupName;
  scoreForm.projectName = row.groupProName;
  scoreForm.schedule = getFinishStatus(row.groupFinish)
  scoreForm.score = row.groupScore;
  if (row.groupNotice == null) {
    scoreForm.notice = "";
  }
  else {
    scoreForm.notice = String(row.groupNotice);
  }
  scoreForm.isApproved = String(row.groupIsAvailable);
  // scoreForm.isApproved = row.isApproved; // 如果没有立项状态，则默认为空字符串
  // 显示对话框
  dialogFormVisible.value = true;

}

const deleteGroup = async (index: number, row: GroupData) => {

  await studentStore.disbandGroup(String(row.studentId));
  ElMessage.success("删除小组成功");
  fetchDataByClassId();
}

//分页相关


const handleSizeChange = (size: any, row: any) => {
  console.log(size, row);
}

const handleCurrentChange = (page: any, size: any) => {
  console.log(page, size);
}

//对话框相关
let dialogFormVisible = ref(false);
const scoreForm = reactive({
  groupId: 0,
  groupName: '',
  projectName: '',
  schedule: '',
  score: 60,
  isApproved: "0", // 是否立项成功
  notice: " "
});
const commitScore = async () => {
  await adminStore.allowAndSetPro({

    groupId: scoreForm.groupId,
    groupIsAvailable: Number(scoreForm.isApproved),
    groupScore: scoreForm.score,
    groupNotice: scoreForm.notice
  });
  await adminStore.fetchTableGroupsData({
    classId: value.value,
    page: page.currentPage,
    pageSize: page.pageSize,
  });
  tableData.value = adminStore.tableGroupsData; // 更新表格数据
  dialogFormVisible.value = false;
}
</script>

<template>
  <div>
    <div class="top">
      <el-select v-model="value" class="m-2" placeholder="班级选择" style="width: 240px">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button type="primary" style="float: right" v-debounce:500="exportScore">导出小组评分</el-button>
    </div>
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="groupName" label="小组名" />
      <el-table-column prop="groupLeader" label="组长用户名" />
      <el-table-column prop="groupProName" label="项目名" />
      <el-table-column prop="groupScore" label="分数" />
      <el-table-column label="立项状态">
        <template #default="{ row }">
          {{ getIsavailableStatus(row.groupIsAvailable) }}
        </template>
      </el-table-column>


      <el-table-column label="完成进度">
        <template #default="{ row }">
          {{ getFinishStatus(row.groupFinish) }}
        </template>
      </el-table-column>

      <el-table-column label="评定" width="150">
        <template #default="scope">
          <el-button size="small" type="danger" v-debounce:500="() => getScore(scope.$index, scope.row)">
            打分
          </el-button>
          <el-button size="small" type="danger" v-debounce:500="() => deleteGroup(scope.$index, scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>



      <!-- 其他列 -->
    </el-table>
    <el-pagination v-model:current-page="page.currentPage" v-model:page-size="page.pageSize" background
      layout="prev, pager, next, jumper" :total="page.total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />
    <!--对话框打分立项    -->

    <el-dialog v-model="dialogFormVisible" title="打分立项表单">
      <el-form :model="scoreForm">
        <el-form-item label="小组名">
          <el-input v-model="scoreForm.groupName" autocomplete="off" readonly />
        </el-form-item>
        <el-form-item label="项目名">
          <el-input v-model="scoreForm.projectName" readonly />
        </el-form-item>
        <el-form-item label="完成进度">
          <el-input v-model="scoreForm.schedule" readonly />
        </el-form-item>
        <el-form-item label="是否立项成功">
          <el-radio-group v-model="scoreForm.isApproved" class="ml-4">
            <el-radio value="1">是</el-radio>
            <el-radio value="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="得分">
          <el-input v-model="scoreForm.score"></el-input>
        </el-form-item>
        <el-form-item label="通知信息">
          <el-input v-model="scoreForm.notice" type="textarea" :rows="4" placeholder="请输入通知信息"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">返回</el-button>
          <el-button type="primary" v-debounce:500="commitScore">确认提交</el-button>
        </span>
      </template>
    </el-dialog>




  </div>
</template>

<style scoped lang="scss">
.top {
  margin-bottom: 15px;
}
</style>